package plenprojects.chatapi;

import org.springframework.web.client.RestTemplate;

public class Session {
	
	private final String rootUrl;
	private final String token;
	private boolean isActive = true;//TODO

	public Session(String rootUrl, String token) {
		
		this.rootUrl = rootUrl;
		this.token = token;
	}
	
	public boolean isValid() throws ConnectionException {
		
		RestTemplate rest = new RestTemplate();
		
		String suffix = String.format(ChatContext.tokenValidSuffix, token);
		
		ServerMessage resp = null;
		
		try {
			
			resp = rest.getForObject(rootUrl + suffix, ServerMessage.class);
			
		}
		catch(Exception e) {
			
			throw new ConnectionException();
		}
		
		Boolean is = (Boolean)resp.getParameter("isvalid");
		
		return is;
	}
	
	public ChatRoom joinRoom(String room) throws ChatException, ConnectionException {
		
		RestTemplate rest = new RestTemplate();
		
		String suffix = String.format(ChatContext.joinRoomSuffix, token, room);
		
		ServerMessage resp = null;
		
		try {
			
			resp = rest.postForObject(rootUrl + suffix, new ServerMessage(), ServerMessage.class);
			
		}
		catch(Exception e) {
			
			throw new ConnectionException();
		}
		
		Boolean success = (Boolean)resp.getParameter("success");
		
		if(!success) {
			
			String error = (String)resp.getParameter("error");
			
			throw new ChatException(error);
		}
		
		return new ChatRoom(room, this);
	}
	
	public void logout() throws ChatException, ConnectionException {
		
		RestTemplate rest = new RestTemplate();
		ServerMessage req = new ServerMessage();
		
		req.setParameter("token", token);
		
		ServerMessage resp = null;
		
		try {
			
			resp = rest.postForObject(rootUrl + ChatContext.logoutSuffix, req, ServerMessage.class);
			
		}
		catch(Exception e) {
			
			throw new ConnectionException();
		}
		
		Boolean success = (Boolean)resp.getParameter("success");
		
		if(!success) {
			
			String error = (String)resp.getParameter("error");
			
			throw new ChatException(error);
		}
	}
	
	public ChatRoom createRoom(String room) throws ChatException, ConnectionException {
		
		RestTemplate rest = new RestTemplate();
		
		String suffix = String.format(ChatContext.createRoomSuffix, token, room);
		
		ServerMessage resp = null;
		
		try {
			
			resp = rest.postForObject(rootUrl + suffix, new ServerMessage(), ServerMessage.class);
			
		}
		catch(Exception e) {
			
			throw new ConnectionException();
		}
		
		Boolean success = (Boolean)resp.getParameter("success");
		
		if(!success) {
			
			String error = (String)resp.getParameter("error");
			
			throw new ChatException(error);
		}
		
		return this.joinRoom(room);
	}
	
	protected String getRootUrl() {
		
		return rootUrl;
	}
	
	protected String getToken() {
		
		return token;
	}
	
}
